//
//  FirendDetailViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "FirendDetailViewController.h"
#import "MyFirendDetailCell.h"
#import "MyFirendData.h"
#import "MyFirendDataManager.h"
#import "UserId.h"
#import "ConsultingChatViewController.h"
#import "ReportViewController.h"
@interface FirendDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
/**
 *  显示好友数据信息
 */
@property (strong, nonatomic) IBOutlet UITableView *firendDetailTableView;
/**
 *  创建数据对象
 */
@property (nonatomic, strong) MyFirendData *myFirendDataObjc;
@end

@implementation FirendDetailViewController

- (MyFirendData *)myFirendDataObjc{
    if (_myFirendDataObjc == nil) {
        _myFirendDataObjc = [[MyFirendData alloc] init];
    }
    return _myFirendDataObjc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.firendDetailTableView.delegate = self;
    self.firendDetailTableView.dataSource = self;
    [self setNaviBarAttribute];
    self.navigationItem.title = @"我的好友";
    self.firendDetailTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.sendMessageButton.layer.masksToBounds = YES;
    self.sendMessageButton.layer.cornerRadius = 2;
    self.cancelAttentionButton.layer.masksToBounds = YES;
    self.cancelAttentionButton.layer.cornerRadius = 2;
    [self loadData];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 30, 23);
    [rightButton setTitle:@"投诉" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(handleRightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction:(UIButton *)sender{
    ReportViewController *reportVC = [[ReportViewController alloc] init];
    reportVC.report_type = @"3";
//    reportVC.reportId=self.myFirendDataObjc.uid;
    reportVC.username=self.myFirendDataObjc.username;
    reportVC.objectids = self.myFirendDataObjc.uid;
    reportVC.reportType=1;
    [self.navigationController pushViewController:reportVC animated:YES];
}


#pragma mark - tableView的代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else {
        return 3;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (kScreenWidth == 414) {
            return 77;
        }else{
            return 64;
        }
    }else{
        if (kScreenWidth == 414) {
            return 54;
        }else{
        return 44;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *firstStr = @"firstFirentCell";
        MyFirendDetailCell *firstCell = [tableView dequeueReusableCellWithIdentifier:firstStr];
        if (!firstCell) {
            if (kScreenWidth == 414) {
                firstCell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendDetailCell" owner:self options:nil] objectAtIndex:2];
                firstCell.firendName.frame = CGRectMake(83, 12, 32, 18);
            }else{
            firstCell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendDetailCell" owner:self options:nil] firstObject];
                firstCell.firendName.frame = CGRectMake(74, 12, 30, 18);
            }
        }
        firstCell.firendName.text = self.myFirendDataObjc.username;
        firstCell.firendName.numberOfLines = 1;
        CGSize size = CGSizeMake(300, 18);
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13],NSFontAttributeName,nil];
        CGSize redSize = [self.myFirendDataObjc.username boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
        //获取当前文本的属性
        if (kScreenWidth == 414) {
            firstCell.firendName.frame = CGRectMake(83, 12, redSize.width + 10, 18);
            firstCell.sexImageView.frame = CGRectMake(83 + redSize.width + 10, 12, 16, 16);
        }else{
            firstCell.firendName.frame = CGRectMake(74, 12, redSize.width + 10, 18);
            firstCell.sexImageView.frame = CGRectMake(74 + redSize.width + 10, 12, 16, 16);
        }
        
        firstCell.firendName.text = self.myFirendDataObjc.username;
        MyNSLog("====%@",self.myFirendDataObjc.avatar);
        [firstCell.headerImageView setImageWithURL:[NSURL URLWithString:self.myFirendDataObjc.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
        firstCell.headerImageView.layer.masksToBounds = YES;
        firstCell.headerImageView.layer.cornerRadius = 3.0f;
        if ([self.myFirendDataObjc.gender isEqualToString:@"男"]){
            firstCell.sexImageView.image = [UIImage imageNamed:@"men"];
        }else if([self.myFirendDataObjc.gender isEqualToString:@"女"]){
            firstCell.sexImageView.image=[UIImage imageNamed:@"women"];
        }else{
            firstCell.sexImageView.hidden = YES;
        }
        MyNSLog("%@", self.myFirendDataObjc.avatar);
        return firstCell;
    }else{
        static NSString *secondStr = @"secondFirendCell";
        MyFirendDetailCell *secondCell = [tableView dequeueReusableCellWithIdentifier:secondStr];
        if (!secondCell) {
            if (kScreenWidth == 414) {
                secondCell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendDetailCell" owner:self options:nil] objectAtIndex:3];
            }else{
                secondCell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendDetailCell" owner:self options:nil] objectAtIndex:1];
            }
        }
        
        if (indexPath.row == 0) {
            if (kScreenWidth == 414) {
                secondCell.firendDetailContent.frame = CGRectMake(74, 18, 231, 18);
            }else{
                secondCell.firendDetailContent.frame = CGRectMake(74, 13, 231, 18);
            }
            secondCell.firendDetailTypeName.text = @"签名";
            secondCell.firendDetailContent.text = self.myFirendDataObjc.bio;
            
        }else if (indexPath.row == 1){
            secondCell.firendDetailTypeName.text = @"地区";
            secondCell.firendDetailContent.text = self.myFirendDataObjc.address;
        }else if (indexPath.row == 2){
            secondCell.firendDetailTypeName.text = @"等级";
            secondCell.firendDetailContent.text = self.myFirendDataObjc.level;
        }
//        else if (indexPath.row == 3){
//            secondCell.firendDetailTypeName.text = @"来源";
////            secondCell.firendDetailContent.text = self.myFirendDataObjc;
//        }
        return secondCell;
    }
    
}


#pragma mark - 网络数据请求 -
- (void)loadData{
    //  清理SDWebImage数据缓存
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/detail/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"uid":self.firendId};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         if ([statusString isEqualToString:@"0"])
         {
             [self showCustomHudSingleLine:@"请求失败"];
         }else
         {
             NSDictionary *encyDic = [responseObject objectForKey:@"data"];
             self.myFirendDataObjc.myuid = [UserId shareUid].uidStr;
             [self.myFirendDataObjc setValuesForKeysWithDictionary:encyDic];             
             MyNSLog("%@", encyDic);
             if ([self.myFirendDataObjc.isfollow intValue] == 1) {
                 // 删除本地的用户头像
                 [[MyFirendDataManager shareInstance] deleteImage:self.myFirendDataObjc.uid withMyUid:self.myFirendDataObjc.myuid];
                 self.navigationItem.title = @"我的好友";
                 [self.cancelAttentionButton setTitle:@"取消关注" forState:UIControlStateNormal];
                 self.cancelAttentionButton.titleLabel.textColor = [UIColor whiteColor];
                 [self.cancelAttentionButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
                 self.sendMessageButton.enabled = YES;
                 [self.sendMessageButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
                 //  存放头像
                 [[MyFirendDataManager shareInstance] setImagePath:self.myFirendDataObjc.avatar withUid:self.myFirendDataObjc.uid withMyUid:self.myFirendDataObjc.myuid];
                 
             }else if ([self.myFirendDataObjc.isfollow intValue] == 0){
                 self.navigationItem.title = @"陌生人";
                 [self.cancelAttentionButton setTitle:@"关注" forState:UIControlStateNormal];
                 self.cancelAttentionButton.titleLabel.textColor = [UIColor blackColor];
                 [self.cancelAttentionButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
                 
                 [self.sendMessageButton setBackgroundColor:[UIColor lightGrayColor]];
                 self.sendMessageButton.enabled = NO;
                 self.sendMessageButton.titleLabel.textColor = [UIColor whiteColor];
             }
             [self.firendDetailTableView reloadData];
         }
         [self hiddenActionView];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         MyNSLog("失败");
         self.sendMessageButton.hidden = YES;
         self.cancelAttentionButton.hidden = YES;
         [self hiddenActionView];
     }];
}

//  也就是取消关注
- (void)deleteMyfirend{
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/unfollowuser/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"uid":self.myFirendDataObjc.uid};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         [self hiddenActionView];
         if ([statusString isEqualToString:@"0"])
         {
             //            [self shouLabel:@"暂无内容"]; //失败
         }else
         {
             [[MyFirendDataManager shareInstance] deleteMyFirendInfo:self.myFirendDataObjc.uid withMyUid:self.myFirendDataObjc.myuid];
             [[MyFirendDataManager shareInstance] deleteImage:self.myFirendDataObjc.uid withMyUid:self.myFirendDataObjc.myuid];
            
            MyNSLog("删除成功");
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self hiddenActionView];
     }];
    
}


//  添加关注
- (void)attentionSb{
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/followuser/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:kPlatform forKey:@"platform"];
    [dic setObject:kVersion forKey:@"version"];
    [dic setObject:self.myFirendDataObjc.uid forKey:@"uid"];
    [manager POST:postURL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self shouLabel:@"添加失败"];
        }else{
            //  存入数据库
            [[MyFirendDataManager shareInstance] addNewFirendInfo:self.myFirendDataObjc];
            //  存放头像
            [[MyFirendDataManager shareInstance] setImagePath:self.myFirendDataObjc.avatar withUid:self.myFirendDataObjc.uid withMyUid:self.myFirendDataObjc.myuid];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}


#pragma mark - 两个button的实现方法 -
// 发消息方法
- (IBAction)sendMessageButtonAction:(UIButton *)sender {
    if ([[UserId shareUid].uidStr isEqualToString:self.myFirendDataObjc.uid]) {
        [self showCustomHudSingleLine:@"自己不可以和自己聊天"];
    }else{
        if ([self.myFirendDataObjc.isfollow intValue] == 1) {
            ConsultingChatViewController *consultChatVC = [[ConsultingChatViewController alloc] init];
            consultChatVC.touid =self.myFirendDataObjc.uid;
            consultChatVC.toTpye = @"1";
            consultChatVC.toMed=@"0";
            consultChatVC.qid=@"0";
            consultChatVC.userName =self.myFirendDataObjc.username;
            consultChatVC.toUserImage =self.myFirendDataObjc.avatar;
            consultChatVC.isFromwhere = 0;
            [self.navigationController pushViewController:consultChatVC animated:YES];
        }else{
        }
    }
}

//  取消关注button方法
- (IBAction)cancelTheAttentionAction:(UIButton *)sender {
    [self isLogin];
}

//  判读登陆状态
- (void)Login
{
    if ([self.myFirendDataObjc.isfollow intValue] == 0) {
        [self attentionSb];
        self.navigationItem.title = @"我的好友";
        [self.cancelAttentionButton setTitle:@"取消关注" forState:UIControlStateNormal];
        self.cancelAttentionButton.titleLabel.textColor = [UIColor whiteColor];
        [self.cancelAttentionButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
        [self.sendMessageButton addTarget:self action:@selector(sendMessageButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.sendMessageButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
        self.sendMessageButton.titleLabel.textColor = [UIColor whiteColor];
        self.sendMessageButton.enabled = YES;
        self.myFirendDataObjc.isfollow = @"1";
        
    }else if ([self.myFirendDataObjc.isfollow intValue] == 1){
        [self deleteMyfirend];
        self.navigationItem.title = @"陌生人";
        [self.cancelAttentionButton setTitle:@"关注" forState:UIControlStateNormal];
        self.cancelAttentionButton.titleLabel.textColor = [UIColor blackColor];
        [self.cancelAttentionButton setBackgroundColor:[UIColor colorWithRed:79 / 255.f green:193 / 255.f blue:233 / 255.f alpha:1.0]];
        [self.sendMessageButton removeTarget:self action:@selector(sendMessageButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.sendMessageButton setBackgroundColor:[UIColor lightGrayColor]];
        self.sendMessageButton.titleLabel.textColor = [UIColor whiteColor];
        self.sendMessageButton.enabled = NO;
        self.myFirendDataObjc.isfollow = @"0";
    }
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
